package cc.atliberty.oa.controller;

import cc.atliberty.oa.pojo.User;
import cc.atliberty.oa.service.UserService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@WebServlet("/user/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取前端提交的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User(username,password);
        if (username == null && password == null){
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
        // 先判断是否用了重复的账户名
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        UserService userService = applicationContext.getBean("userService", UserService.class);
        int checked = userService.checkUser(username);
        if (checked != 1){
            int count = userService.insertUser(user);
            if (count == 1){
                response.getWriter().print("<script type=\"text/javascript\">alert(\"注册成功\")<script>");
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        } else {
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }
}
